#pragma once
 
#include <iostream>
#include <memory>
#include <string>
#include <sys/epoll.h>
#include "Socket.hpp"
#include "Log.hpp"
#include "Epoller.hpp"
#include "Nocopy.hpp"

static const uint32_t EVENT_IN = EPOLLIN;
static const uint32_t EVENT_OUT = EPOLLOUT;
static const int num = 64;
static const uint16_t defaultport = 28080;

class EpollServer : public Nocopy{
public:
    EpollServer(const uint16_t &port=defaultport)
    :_port(port)
    ,_listensock_ptr(new MySocket())
    ,_epoller_ptr(new Epoller())
    {}

    bool Init(){
        _listensock_ptr->Socket();
        _listensock_ptr->Bind(_port);
        _listensock_ptr->Listen();

        mylog(INFO, "socket create success..., fd is %d", _listensock_ptr->Fd());
        return true;
    }

private:
    void Accepter(){
        std::string clientip;
        uint16_t clientport;
        int newfd = _listensock_ptr->Accept(&clientip, &clientport);
        if (newfd < 0){
            mylog(Error, "link accept error...");
            return;
        }
        mylog(INFO, "get a new link, fd is %d", newfd);

        // 建立连接后不能立即读取，需要等待读事件就绪后才能读取
        // 将连接fd以及关心的读事件添加到epoll模型中
        _epoller_ptr->EpollerUpDate(EPOLL_CTL_ADD, newfd, EVENT_IN);
    }

    void Reader(const int &fd){
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if(n < 0){
            mylog(Error, "read error, close fd is %d", fd);
            // 关闭某个fd时，需要先从epoll模型中删除，然后才能关闭，否则删除时fd就是不合法的
            _epoller_ptr->EpollerUpDate(EPOLL_CTL_DEL, fd, 0);
            close(fd);
            return;
        }
        else if (n == 0){
            mylog(INFO, "client quit, me to, close fd is %d", fd);
            _epoller_ptr->EpollerUpDate(EPOLL_CTL_DEL, fd, 0);
            close(fd);
            return;
        }
        else{
            buffer[n] = 0;
            std::cout << "get a message: " << buffer << "client fd is: " << fd << std::endl;
        }
    }

    void EventEventDispatcher(const int &n){
        for (int i = 0; i < n; i++){
            int fd = _revents[i].data.fd;
            uint32_t events = _revents[i].events;
            if (events & EVENT_IN){
                // 根据当前fd是否是socket套接字来判断是连接事件还是读事件
                if (fd == _listensock_ptr->Fd()){
                    Accepter();
                }
                else{
                    Reader(fd);
                }
            }
            else if (events & EVENT_OUT){

            }
            else{

            }
        }
    } 

public:

    void Start(){
        int sock = _listensock_ptr->Fd();
        _epoller_ptr->EpollerUpDate(EPOLL_CTL_ADD, sock, EVENT_IN);
        while(true){
            int n = _epoller_ptr->EpollerWait(_revents, num);
            if(n < 0){
                mylog(Error, "epoll wait error...");
            }
            else if (n == 0){
                mylog(INFO, "epoll wait time out...");
            }
            else{
                mylog(INFO, "There is an event triggered...");
                EventEventDispatcher(n);
            }
        }
    }

    ~EpollServer()
    {
        if (_listensock_ptr->Fd() >= 0){
            _listensock_ptr->Close();
        }
    }
private:
    uint16_t _port;
    std::shared_ptr<MySocket> _listensock_ptr;    // socket套接字
    std::shared_ptr<Epoller> _epoller_ptr;        // epoll模型
    struct epoll_event _revents[num];
};